package cn.wyl.controller;

import cn.wyl.User;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//用户服务：暴露接口给订单访问
@RestController
@RefreshScope  //刷新配置
public class UserController {

    //修改了Nacos中的配置文件，Controller中读取到的配置`temp.notify`将会自动变化。
    @Value("${temp.notify}")
    private String notify;

    @RequestMapping(value = "/user/{id}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    //限流降级 熔断降级 通过`@SentinelResource`的value属性为资源取名为 “user”
    @SentinelResource(value="user",blockHandler="exceptionHandler",fallback = "fallbackHandler")
    public User getById(@PathVariable("id") Long id){
        //int i=1/0;
        return new User(id,"zs","我是zs,notify:"+notify);
    }

    // 限流降级 : 参数要和 被降级的方法参数一样
    public User exceptionHandler(@PathVariable("id") Long id, BlockException ex){
        ex.printStackTrace();
        return new User(-1L,"限流了","限流了");
    }

    // 熔断降级，参数和返回值与被熔断方法一致
    public User fallbackHandler(@PathVariable Long id){
        return new User(-1L,"熔断了","熔断了");
    }
}
